package wwl.lsf.hellospringboot.test.nio.netty聊天;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;

public class ChatClient {

  private String host;

  private int port;


  public ChatClient(String host, int port) {

    this.host = host;
    this.port = port;

  }

  public void run() {

    NioEventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap bootstrap = new Bootstrap();

      bootstrap.group(group)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {

              ChannelPipeline pipeline = socketChannel.pipeline();

              pipeline.addLast("decoder", new StringDecoder());
              pipeline.addLast("encoder", new StringEncoder());
              pipeline.addLast("handler", new ChatClientHandler());
            }
          });

      Channel channel = bootstrap.connect(host, port).sync().channel();
      System.out.println(channel.localAddress().toString()+"起来了");
      Scanner scanner = new Scanner(System.in);
      while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        channel.writeAndFlush(s);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      group.shutdownGracefully();
    }

  }

  public static void main(String[] args) {
    new ChatClient("127.0.0.1", 9999).run();
  }

}
